package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.guns.sys.core.constant.cache.CacheKey;
import cn.stylefeng.guns.sys.modular.system.model.result.DDEmpResult;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class DDUtil {

    private static final Logger log = LoggerFactory.getLogger(DDUtil.class);

    private static final String URL_DDgettoken="https://oapi.dingtalk.com/gettoken";
    private static final String DD_APPKEY="dingvvrsivpeg6bqm4qb";
    private static final String DD_APPSECRET="wly_IoMnP0QXZzaWh-NiSOUxZJgpmDzZeKyy6LPQMktm9iO65RfO14LVYUliokL-";

    private static final int SUCCESS_CODE=0;
    @Resource
    private RedisUtils redisUtils;

    /**
     *
     * 根据部门id获取部门员工
     */
    public List<DDEmpResult>  queryDingdingEmpBydeptid(Long deptid) throws Exception {
        //获取token
        List<DDEmpResult> listAll = new ArrayList<DDEmpResult>();
        boolean hasMore = false;
        Long p = 0L;
        do{
            DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
            OapiUserSimplelistRequest req2 = new OapiUserSimplelistRequest();
            req2.setDepartmentId(deptid);
            req2.setOffset(p);
            req2.setSize(100L);
            req2.setHttpMethod("GET");
            OapiUserSimplelistResponse rsp2 = client2.execute(req2, getToken());

            Map map2=(Map) JSON.parse(rsp2.getBody());
            Integer errcode=(Integer) map2.get("errcode");
            if(errcode==0){
                Object userlist = map2.get("userlist");
                List<DDEmpResult>  list= JSON.parseArray(userlist.toString(), DDEmpResult.class);
                listAll.addAll(list);
                hasMore= (boolean) map2.get("hasMore");
                p++;
            }else {
                hasMore = false;
            }
        }while (hasMore);
        return listAll;
    }

    /**
     * 获取token
     * @return
     * @throws ApiException
     */
    public String getToken() throws Exception {
        String token = (String) redisUtils.get(CacheKey.DINGDING_TOKEN);
        if(ToolUtil.isEmpty(token)){
            DingTalkClient client0 = new DefaultDingTalkClient(URL_DDgettoken);
            OapiGettokenRequest req0 = new OapiGettokenRequest();
            req0.setAppkey(DD_APPKEY);
            req0.setAppsecret(DD_APPSECRET);
            req0.setHttpMethod("GET");
            OapiGettokenResponse rsp0 = client0.execute(req0);

            Map result = (Map) JSON.parse(rsp0.getBody());
            Integer code = (Integer) result.get("errcode");
            if(code!=0){
                log.error("钉钉获取token失败,{}",result.get("errmsg"));
                return null;
            }
            token = result.get("access_token").toString();
            if(ToolUtil.isNotEmpty(token)){
                redisUtils.set(CacheKey.DINGDING_TOKEN,token,7200);
            }

        }
        return token;
    }

    /**
     * 获取钉钉部门列表
     * @return
     * @throws Exception
     */
    public JSONArray listDepts() throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId("1");
        request.setHttpMethod("GET");
        request.setFetchChild(true);
        OapiDepartmentListResponse rsp = client.execute(request, getToken());
        String body = rsp.getBody();
        JSONObject obj = JSON.parseObject(body);
        Integer errcode = (Integer) obj.get("errcode");
        if(SUCCESS_CODE==errcode.intValue()){
            JSONArray list = (JSONArray) obj.get("department");
            return list;
        }else{
            log.error("获取部门列表报错,{}",obj.get("errmsg"));
            return null;
        }

    }

    /**
     * 根据部门id获取用户
     * @param deptid
     * @return
     * @throws Exception
     */
    public JSONArray getUsersByDeptid(String deptid) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
        OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
        req.setDeptId(deptid);
        req.setHttpMethod("GET");
        OapiUserGetDeptMemberResponse rsp = client.execute(req, getToken());
        String body = rsp.getBody();
        JSONObject obj = JSON.parseObject(body);
        Integer errcode = (Integer) obj.get("errcode");
        if(SUCCESS_CODE==errcode.intValue()){
            JSONArray list = (JSONArray) obj.get("userIds");
            return list;
        }else{
            log.error("获取部门用户列表报错,{}",obj.get("errmsg"));
            return null;
        }
    }

    /**
     * 根据部门id获取用户
     * @param deptid
     * @return
     * @throws Exception
     */
    public JSONArray getUsersArrayByDeptid(Long deptid) throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
        OapiUserListbypageRequest req = new OapiUserListbypageRequest();
        req.setLang("zh_CN");
        req.setDepartmentId(deptid);
        req.setOffset(1L);
        req.setSize(1L);
        req.setOrder("entry_asc");
        req.setHttpMethod("GET");
        OapiUserListbypageResponse rsp = client.execute(req, getToken());
        String body = rsp.getBody();
        JSONObject obj = JSON.parseObject(body);
        Integer errcode = (Integer) obj.get("errcode");
        if(SUCCESS_CODE==errcode.intValue()){
            JSONArray list = (JSONArray) obj.get("userlist");
            return list;
        }else{
            log.error("获取部门用户列表报错,{}",obj.get("errmsg"));
            return null;
        }
    }

    public static int diaoyong_cishu=0;
    /**
     * 根据用户id获取详情
     * @param userid
     * @return
     * @throws Exception
     */
    public JSONObject getDetailByUserid(String userid) throws Exception {
        if(diaoyong_cishu>3900){
            diaoyong_cishu=-1;
            Thread.sleep(5000);
        }
        diaoyong_cishu++;
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userid);
        request.setHttpMethod("GET");
        OapiUserGetResponse rsp = client.execute(request, getToken());
        String body = rsp.getBody();
        JSONObject obj = JSON.parseObject(body);
        Integer errcode = (Integer) obj.get("errcode");
        if(SUCCESS_CODE==errcode.intValue()){
            return obj;
        }else{
            log.error("获取用户详情报错,{}",obj.get("errmsg"));
            return null;
        }
    }


}
